﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.ConstrainedExecution;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace WinNMPForms
{
    internal class Nginx
    {
        // nginx 所在目录
        private static readonly string exeName = "nginx";
        private string appDir;
        private string path;
        private string version;
        protected string configPath;
        private bool isRun = false;
        private bool isExits = false;

        public string AppDir { get => appDir; set => appDir = value; }
        public string Version { get => version; set => version = value; }
        public string Path { get => path; set => path = value; }
        public bool IsRun { get => isRun; set => isRun = value; }
        public bool IsExits { get => isExits; set => isExits = value; }

        public Nginx()
        {
            appDir = ConfigurationManager.AppSettings.Get("nginx_dir").Replace("/", "\\");
            if (appDir.Substring(appDir.Length - 1, 1).Equals("\\") == false)
            {
                appDir += "\\";
            }
            // Console.WriteLine(appDir);

            path = this.appDir + "nginx.exe";

            if (File.Exists(this.Path) != false)
            {
                isExits = true;
                configPath = this.appDir + "/conf/nginx.conf";

                Process[] myProcess = Process.GetProcessesByName(exeName);

                if (myProcess.Length > 0)
                {
                    this.isRun = true;
                }

                string ver = ShowVersion();

                if (ver != null)
                {
                    version = ver.Replace("nginx version: nginx/", "");
                }
            }

        }

        public void Start()
        {
            ProcessRun.NoWaitExitStartCmd(this.appDir, "start", exeName);

            this.isRun = true;
        }

        public void Stop()
        {
            ProcessRun.ProcessStop(exeName);

            this.isRun = false;
        }

        internal string ShowVersion()
        {
            // nginx 控制台输出用的是 StandardError
            (_, string se) = ProcessRun.ProcessStart(this.path, "-v");

            return se;
        }

        public string CheckConf()
        {
            // nginx 控制台输出用的是 StandardError
            (_, string se) = ProcessRun.ProcessStart(this.appDir, exeName, "-t");

            return se;
        }

        internal void EditConf()
        {
            System.Diagnostics.Process.Start(this.configPath);
        }

        public List<string> ViewSite()
        {
            List<string> linkList = new List<string>();

            try
            {
                // Open the text file using a stream reader.
                using (var sr = new StreamReader(configPath))
                {
                    string config = sr.ReadToEnd();
                    config = config.Replace("\r\n", "\n").Replace("\n\n", "\n").Replace("\n\n", "\n");
                    string[] linkArray = config.Split('\n');

                    for (int i = 1; i < linkArray.Length - 1; i++)
                    {

                        string link = linkArray[i].Trim();
                        if (link == "" || link.Substring(0, 1) == "#")
                        {
                            continue;
                        }

                        if (link.StartsWith("listen"))
                        { 
                            link = link.Substring(0, link.Length-1).Replace("listen", "").Replace(" ", "").Replace(";", "");
                            i++;
                            string servername = linkArray[i].Replace("server_name", "").Replace(" ", "").Replace(";", "");
                            link = "http://" + servername + ":" + link + "/";
                            // Console.WriteLine(link);
                            linkList.Add(link);
                        }
                    }

                    return linkList;
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }

            return linkList;
        }
    }
}
